package com.xiaoxu.intranetweb.config.request;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private UserInfoDao userInfoDao;
   // 在请求处理之前进行调用（Controller方法调用之前）
   // 返回true才会继续执行，返回false则取消当前请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        检查请求里是否有token,并且token是否合法
        try {
            String token = request.getHeader("Authorization");
            if (token.isEmpty()) {
                response.setStatus(200);
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                out.write(SzResult.tokenError("token为空").toString());
                out.flush();
                out.close();
                return false;
            }else {
               if (StpUtil.getLoginIdByToken(token) == null) {
                   response.setStatus(200);
                   response.setContentType("application/json;charset=UTF-8");
                   response.setCharacterEncoding("UTF-8");
                   PrintWriter out = response.getWriter();
                   out.write(SzResult.tokenError("token不合法或登录过期").toString());
                   out.flush();
                   out.close();
                   return false;
               }
                    if (userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString()) == null) {
//                        System.out.println("用户不存在");
                        response.setStatus(200);
                        response.setContentType("application/json;charset=UTF-8");
                        response.setCharacterEncoding("UTF-8");
                        PrintWriter out = response.getWriter();
                        out.write(SzResult.tokenError("用户不存在").toString());
                        out.flush();
                        out.close();
                        return false;
                    }
                }
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
//            PrintWriter out = response.getWriter();
//            out.write(SzResult.error(e.getMessage()).toString());
//            out.flush();
//            out.close();
            return false;
        }
        return true;
    }
    // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    // 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
//重定向到login
//    public void redirectLogin(HttpServletResponse response) throws Exception {
//        response.sendRedirect("/login");
//    }

}